var baseApp = angular.module ( "base" );
// ab-page
baseApp.directive ( 'abPage' , function ( $timeout , $injector ) {

	return {
	    restrict : 'EA' ,
	    scope : {
	        list : "=" ,// 目标页面scope中的list对象
	        url : "=" ,// URL地址
	        pageSize : "=" ,// 分页大小
	        params : "=" ,// 需要传递的参数对象
	        isInitData : "=" ,// 是否初始化
	        parent : "=" ,// 原页面 scope 对象的父级
	        callback : "=" , // 回调函数
	        pageScope : "=" ,
	    } ,
	    template : '<nav ng-show="page.count>0" class="pageBoxNav">' + '<div class="pageBox page-{{pageColor}}">' +
	    // 首页 - begin
	    '<a ng-click="page.pageNum=1" class="firstPage pointer" ng-if="page.pageNum!=1">首页</a>' +
	    // 首页 - end
	    // 上一页 - begin
	    '<a  aria-label="Previous"  class="prePage pointer" ng-if="page.pageNum!=1" ng-click="page.pageNum=(page.pageNum-1)" title="上一页">' + '<span class="glyphicon glyphicon-backward" ></span>' + '</a>' +
	    // 上一页 - end
	    // 页码 - begin
	    '<a ng-click="clickPageFn(p,$index)" ng-repeat="p in page.pages" ng-class="{cur:page.pageNum==p.page}" class="{{p.cls}} mb5">{{p.page}}</a>' +
	    // 页码 - end
	    // 下一页 - begin
	    '<a ng-click="page.pageNum=(page.pageNum+1)" ng-if="page.pageNum!=page.pageCount" class="nextPage pointer" title="下一页">' + '<span class="glyphicon glyphicon-forward"></span>' + '</a>' +
	    // 下一页 - end
	    // 最后一页 - begin
	    '<a ng-click="page.pageNum=page.pageCount" ng-if="page.pageNum!=page.pageCount" class="lastPage pointer ">尾页</a>' +
	    // 最后一页 - end
	    '<span class="pageMsg">' + '共{{page.count}}条&nbsp;{{page.pageNum}}页/{{page.pageCount}}页' + '</span>' +
	    // 分页 - begin
	    '<span title="每页的大小">' + '<select ng-model="page.pageSize" ab-parse-data class="pageSize" ng-options="p.k as p.v for p in basePage.pageSizeOptions">' + '</select>' + '</span>' +
	    // 分页 - end
	    '<span class="ml10 toPage">' + '<input type="text" ng-model="toPage" class="form-control "/>' + '</span>' + '<a class="ml10 pointer go" ng-click="toPageFn()">' + 'Go' + '</a>' +
	    // 跳转到指定页面 -- end
	    '</nav>' ,
	    replace : true ,
	    link : function ( scope , elm , attrs ) {

		    var baseService = $injector.get ( "baseService" );
		    scope.base = baseService;
		    scope.pageScope = scope;
		    if ( scope.parent ) {
			    scope.parent.pageScope = scope;
		    }
	    	scope.pageColor = scope.pageColor || "primary";
	    	var basePage = {
                pageSize : "20" ,
                pageSizeArray : ["5","10","15","20","30","50","75","100","1000"],
                pageSizeOptions : [],
                pageNum : 1 ,
                piceSize : 4
            } ;
	    	basePage.pageSizeArray.forEach(function(value, index) {
	    		basePage.pageSizeOptions.push({
	    			k:value,
	    			v:value
	    		})
	        })
	    	
	    	basePage.pageSize = scope.pageSize || basePage.pageSize;
	    	scope.basePage = basePage;
		    scope.list = scope.list || [ ];
		    var pushNumToPage = function ( page , startPage , count ) {
			    count = count || ( startPage + page.piceSize );
			    for ( var i = startPage ; i < count ; i++ ) {
				    var t = {};
				    t.page = i;// 页码
				    t.type = 0;// 类型 0:页码,1:第一个省略号,2:第二个省略号
				    t.cls = "normalPage";// class样式
				    page.pages.push ( t );
			    }
		    };
		    var pageFn = function ( page ) {

			    page = page || angular.extend ( {} , true , basePage );
			    scope.list = scope.list || [ ];
			    page.count = page.count == null ? scope.list.length : page.count;
			    // page.count=50;
			    page.pageCount = Math.floor ( ( page.count + parseInt ( page.pageSize ) - 1 ) / parseInt ( page.pageSize ) );
			    page.pages = [ ];
			    if ( page.pageCount <= 3 * page.piceSize ) {
				    pushNumToPage ( page , 1 , page.pageCount + 1 );
			    } else if ( page.pageCount > 3 * page.piceSize ) {
				    /**
					 * 计算起始页的页码
					 */
				    pushNumToPage ( page , 1 );
				    if ( !scope.page.noOmit1 ) {
					    page.pages.push ( {
					        page : "..." ,
					        type : 1 ,
					        cls : "omit"
					    } );
				    }

				    /**
					 * 计算中段页的页码
					 */
				    if ( !scope.page.middelStartPage ) {
					    scope.page.middelStartPage = parseInt ( ( scope.page.pageCount - scope.page.piceSize ) / 2 );
				    }

				    pushNumToPage ( page , scope.page.middelStartPage );
				    if ( !scope.page.noOmit2 ) {
					    page.pages.push ( {
					        page : "..." ,
					        type : 2 ,
					        cls : "omit"
					    } );
				    }

				    /**
					 * 计算尾部页的页码
					 */
				    pushNumToPage ( page , page.pageCount - page.piceSize + 1 );

			    }
			    scope.page = page;
		    };
		    /**
			 * 页码的点击事件
			 */
		    scope.clickPageFn = function ( p , index ) {

			    var halfPice = parseInt ( scope.page.piceSize / 2 ) + 1;
			    switch ( p.type ) {
				    case 0 :
					    scope.page.pageNum = p.page;
				    break;
				    case 1 :// 点击第一个省略号
					    scope.page.pageNum = scope.page.pages[index + 1].page - halfPice;
					    if ( scope.page.pageNum <= 0 )
						    scope.page.pageNum = 1;
					    scope.calcuMiddelStartPage ( );
				    break;
				    case 2 :// 点击第二个省略号
					    if ( ( scope.page.middelStartPage + scope.page.piceSize ) >= ( scope.page.pageCount - scope.page.piceSize + 1 ) ) {
						    scope.page.pageNum = scope.page.pageNum + 1;
					    } else {
						    scope.page.pageNum = scope.page.pages[index - 1].page + halfPice;
					    }
					    scope.calcuMiddelStartPage ( );
				    break;
			    }

		    };
		    /**
			 * 计算
			 */
		    scope.calcuMiddelStartPage = function ( ) {

			    if ( scope.page.pageCount <= 3 * scope.page.piceSize )
				    return;
			    scope.page.noOmit1 = false;
			    scope.page.noOmit2 = false;
			    scope.page.middelStartPage = scope.page.pageNum - Math.floor ( scope.page.piceSize / 2 );
			    if ( ( scope.page.middelStartPage + scope.page.piceSize ) >= ( scope.page.pageCount - scope.page.piceSize + 1 ) ) {
				    scope.page.middelStartPage = scope.page.pageCount - scope.page.piceSize * 2 + 1;
				    scope.page.noOmit2 = true;
			    } else if ( scope.page.middelStartPage < ( 2 + scope.page.piceSize ) ) {
				    scope.page.middelStartPage = scope.page.piceSize + 1;
				    scope.page.noOmit1 = true;
			    }
		    };
		    pageFn ( );
		    scope.pageFn = pageFn;
		    scope.targetList = [];
		    scope.setPageData = function ( resultList ) {

			    if ( scope.url ) {
				    scope.list = resultList;
			    } else {
				    var start = ( scope.page.pageNum - 1 ) * parseInt ( scope.page.pageSize ) + 1;
				    var end = start + parseInt ( scope.page.pageSize );
				    for ( var i = start ; i < end ; i++ ) {
					    if ( scope.list[i - 1] ) {
						    scope.targetList.push ( scope.list[i - 1] );
					    } else {
						    break;
					    }
				    }
			    }
			    if ( scope.parent )
				    scope.parent.page = scope.page;
		    };
		    /**
			 * 跳转到某一页
			 */
		    scope.toPageFn = function ( ) {

			    if ( !scope.toPage ) {
				    $.Dialog.error ( "请输入跳转页数!" );
				    return;
			    }
			    if ( scope.toPage <= 1 ) {
				    scope.toPage = 1;
			    }
			    if ( scope.toPage > scope.page.pageCount ) {
				    scope.toPage = scope.page.pageCount;
			    }
			    scope.page.pageNum = scope.toPage;
		    };

		    scope.getPageData = function ( ) {

			    if ( scope.lockPost )
				    return;
			    var page = scope.page;
			    var params = {
			        // pageNum : page.pageNum,
			        // pageNo : page.pageNum,
			        curPage : page.pageNum ,
			        pageSize : page.pageSize
			    };
			    if ( scope.params ) {
				    params = angular.extend ( {} , params , scope.params );
			    }
			    if ( scope.targetList ) {
				    scope.targetList = [ ];
			    }
			    if ( scope.url ) {
				    scope.lockPost = true;
				    if ( scope.noPage ) {
					    params.pageSize = 2000;
				    }
				    // params.pageSize = 1;
				    baseService.post ( scope.url , params).then(function ( data ) {

					    scope.lockPost = false;
					    if ( !data ) {
						    $.Dialog.error ( "系统异常" );
						    return;
					    }
					    var isNoPage = data.data&&!data.data.list && data.data instanceof Array;
					    if ( data.isOk ) {
						    if ( isNoPage ) {
					    		data.list = data.data;
					    		data.count = data.data.length;
						    }else if(data.hasOwnProperty("data")){
					    		data = data.data;
					    	}
					    } else if ( data.code ) {
						    $.Dialog.error ( data.msg );
						    return;
					    }

					    if ( typeof data.list == "string" ) {
						    data.list = JsonUtil.ps (data.list.replaceAll ( "\\\\" , "" ));
					    }
					    scope.page = scope.page || angular.extend ( {} , true , basePage );
					    if ( data.pageVo ) {
						    scope.page.count = data.pageVo.count;
						    pageFn ( scope.page );
						    scope.setPageData ( data.pageVo.list );
					    } else {
					    	scope.page.count = data.count;
						    scope.setPageData ( data.content || data.list );
						    pageFn ( scope.page );
					    }
					    window.exportExcel = scope.exportExcel;
					    scope.$broadcast ( 'pageDataLoaded' , {
						    list : data.list
					    } );
					    if ( scope.parent && scope.parent.$broadcast ) {
						    scope.parent.$broadcast ( 'pageDataLoaded' , {
							    list : data.list
						    } );
					    }
					    // 除掉对话框中需要隐藏的东西
					    if(typeof isFromDialogModal != "undefined" && isFromDialogModal=="true"){
					    	removeDialogDiv();
					    }
					    scope.callback && scope.callback.call ( scope.$parent , data );
					    scope.pageScope&&scope.pageScope.dataInitedCallBack && scope.pageScope.dataInitedCallBack ( scope.$parent , data );
				    	
				    });
			    } else if ( scope.list ) {
				    scope.page.count = scope.list.length;
				    pageFn ( scope.page );
				    scope.setPageData ( scope.list );
				    window.exportExcel = scope.exportExcel;
			    }
		    };
		    scope.$watch ( "params" , function ( newValue , oldValue ) {

			    if ( newValue === oldValue || scope.loadByBro ) {
				    return;
			    }
			    scope.page.pageNum = 1;
			    scope.getPageData.call ( this , {} );
		    } , true );
		    scope.$watch ( "list" , function ( newValue , oldValue ) {

			    if ( newValue === oldValue || scope.url || scope.loadByBro ) {
				    return;
			    }
			    scope.page.pageNum = 1;
			    scope.getPageData.call ( this , {} );
		    } , true );
		    scope.$watch ( "page.pageNum" , function ( newValue , oldValue ) {

			    if ( newValue == oldValue || scope.loadByBro ) {
				    return;
			    }
			    scope.getPageData.call ( this , {} );
			    scope.calcuMiddelStartPage.call ( this , {} );
		    } );
		    scope.$watch ( "page.pageSize" , function ( newValue , oldValue ) {

			    if ( newValue == oldValue || scope.loadByBro ) {
				    return;
			    }
			    scope.page.pageNum = 1;
			    pageFn ( scope.page );
			    scope.getPageData.call ( this , {} );
		    } );
		    scope.$on ( "setPageScope" , function ( event , data ) {

			    scope = $.extend ( scope , {} , data );
		    } );
		    scope.$on ( "pageDataChange" , function ( event , msg ) {

			    scope.getPageData.call ( this , {} );
		    } );
		    scope.unWatchInitData = scope.$watch ( "isInitData" , function ( newValue , oldValue ) {

			    if ( newValue == 1 && newValue != oldValue ) {
				    scope.getPageData.call ( this , {} );
				    scope.unWatchInitData ( );
			    }
		    } );
		    scope.isInitData && scope.getPageData ( );
	    }
	};
} );